if (!cms24k) {
	var cms24k = {}
};
$.extend(true, cms24k, {
	living : function() {
		return cms24k.isDef(typeof (k_edit));
	},
	normalAlert  : window.alert,
	isDef : function(value) {
		return value == "undefined";
	},
	templateEngine : function(html, options) {
	    var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
	    var add = function(line, js) {
	        js? (code += line.match(reExp) ? line + '\n' : 'r.push(this.' + line + ');\n') :
	            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
	        return add;
	    }
	    while(match = re.exec(html)) {
	        add(html.slice(cursor, match.index))(match[1], true);
	        cursor = match.index + match[0].length;
	    }
	    add(html.substr(cursor, html.length - cursor));
	    code += 'return r.join("");';
	    return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
	}
});
$.ajaxSetup({ cache: false });



function search(key,target) {
 	if ('' != key) {
		window.location = '/'+target + '/view/1/' + key;
	}

}
function login(){
	
	var isForm = true;
	var form = $("#loginForm");
	if (form.length ==0){
	form = $(this).parents("form:first");
 	}
  	var data ;

	if($(form).get(0).tagName == 'DIV'){
		data  = $('#loginForm :input').serialize();
	}else{
		data  = form.serialize();
	} 
	
		$
			.ajax({
				type : "POST",
				url : "/pub-member/login/",
				data : data,
				dataType : "json",
				success : function(data) {
					if (data
							&& data.state
							&& (data.state
									.indexOf("ERROR") != -1)) {
						alert(data.message);
					} else {
						
						var reload =  (form).attr('reload');
						if (reload){
							location.reload();
						}else{
							
							
							if (typeof (loginURL) == 'undefined') {
								var redirectURL = (form).attr("url");
 								if (redirectURL){
									window.location.href = redirectURL;									
								}else{
									window.location.href = '/user-announce/';									
								}
								

							} else {
								window.location.href = loginURL;
							}
							}
					}
				}
			});
	}
function cleanFrom(form){
	form.find("input:not([type=button],[type=submit]),select,textarea").val("");
}

function showMessage(msg,form){
	var show="";
	if (form){
		var message = form.attr('message');
		if (message){
			show = message;
		}else{
			show = msg;
		}
	}else{
		show = msg;
	}
	alert(show);
	
	
}

function processForm(form){
	var x = 	$(form).find("img.captcha");
	if (x){
		x.attr('src',x.attr('src'));		
	}
 	var processed = false;
	if (form){
		var attr = form.attr('reload');
		if (attr){
			location.reload();
		}
		attr = form.attr('redirect');
		if (attr){
			window.location.href= attr;
 		}
	    attr = form.attr('clean');
	    if (attr){
	    	cleanFrom(form);
 	    }
		attr = form.attr('hide');
		if (attr){
			$(form).hide();
			$( "html,body").animate({ "scrollTop" : 0 }, 600);
			return;
  		}}
}




function isEmail(str){
    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
    return reg.test(str);
}
function validateForm(form){
	
 	if (form.valid){
		var x = (form).valid();
 		if (!x){
		//	alert("please validate your input");
 			return false;
		}else{
			return true;
		}
		
	}else{
	//	console.dir("no valid");
		return true;
	}
 }


function reloadcapcha() {
	var url = '/captcha/?' + new Date().getTime();
	$('.captcha').attr('src', url);
}
$(document)
		.ready(
				function() {
				$("select.auto-country").each(function(step,value){
					if (countries){
						$(countries).each(function(s,v){
								
							   $(value).append($('<option>', { 
							        value: v.name,
							        text : v.name 
							    }));
							
							
						});
						$(value).val("Singapore");
						
					}
					
				});
				
				$("select.auto-country-id").each(function(step,value){
					if (countries){
						var singaporeId;
						$(countries).each(function(s,v){
								
							   $(value).append($('<option>', { 
							        value: v.id,
							        text : v.name
							    }));
							   if (v.name == 'Singapore'){
								   singaporeId = v.id;
							   }
						});
						if (singaporeId){
							$(value).val(singaporeId);							
						}

						
					}
					
				});	
				
				var x =0; y =0;
				$(document).delegate("","mousemove",function(e){
					 
						x = e.pageX;
						y = e.pageY;
						
				});
					
					
					
				if ($.pnotify) {
					
					var bootstrap_enabled = (typeof $().modal == 'function');
						
						window.alert = function(message) {
							$
									.pnotify({
										title : 'Notice',
										text : message,
										delay: 2000,
										history: false,
										before_open: function(pnotify){
										    pnotify.css({
										      "top": y - $(document).scrollTop() - 100, 
										      "left": x-$(document).scrollLeft()-300
										    });
										  },
										styling : (bootstrap_enabled)?'bootstrap':'jqueryui',
										animation : {
											effect_in : function(status,
													callback, pnotify) {
												var source_note = 'Always call the callback when the animation completes.';
												var cur_angle = 0, cur_opacity_scale = 0;
												var timer = setInterval(
														function() {
															cur_angle += 10;
															if (cur_angle == 360) {
																cur_angle = 0;
																cur_opacity_scale = 1;
																clearInterval(timer);
															} else {
																cur_opacity_scale = cur_angle / 360;
															}
															pnotify
																	.css(
																			{
																				'-moz-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'-webkit-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'-o-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'-ms-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'filter' : ('progid:DXImageTransform.Microsoft.BasicImage(rotation='
																						+ (cur_angle / 360 * 4) + ')')
																			})
																	.fadeTo(
																			0,
																			cur_opacity_scale);
															if (cur_angle == 0)
																callback();
														}, 20);
											},
											effect_out : function(status,
													callback, pnotify) {
												var source_note = 'Always call the callback when the animation completes.';
												var cur_angle = 0, cur_opacity_scale = 1;
												var timer = setInterval(
														function() {
															cur_angle += 10;
															if (cur_angle == 360) {
																cur_angle = 0;
																cur_opacity_scale = 0;
																clearInterval(timer);
															} else {
																cur_opacity_scale = cur_angle / 360;
																cur_opacity_scale = 1 - cur_opacity_scale;
															}
															pnotify
																	.css(
																			{
																				'-moz-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'-webkit-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'-o-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'-ms-transform' : ('rotate('
																						+ cur_angle
																						+ 'deg) scale('
																						+ cur_opacity_scale + ')'),
																				'filter' : ('progid:DXImageTransform.Microsoft.BasicImage(rotation='
																						+ (cur_angle / 360 * 4) + ')')
																			})
																	.fadeTo(
																			0,
																			cur_opacity_scale);
															if (cur_angle == 0) {
																pnotify
																		.hide();
																callback();
															}
														}, 20);
											}
										}
									});

						};
					}
					
					
					
					
					
					if (cms24k.living()) {
						if ($.datepicker) {
							$(".datepicker").each(function(){
								var pattern = 'dd/mm/yy';
								var this_pattern = $(this).attr('pattern');
								var month = ("true" == $(this).attr('month'))
								var year  =  ("true" == $(this).attr('year'));
  								if (this_pattern){
									pattern = this_pattern
								}
								$(this).datepicker({
									dateFormat : pattern,
									showOtherMonths : true,
									changeMonth: month,
									changeYear: year
 								});
									
								
							});
						}
						if ($.fn.datetimepicker){
							$(".datetimepicker").each(function(){
								var pattern = 'dd/mm/yy';
								var this_pattern = $(this).attr('pattern');
								if (this_pattern){
									pattern = this_pattern
								}
								$(this).datetimepicker({
									dateFormat : pattern,
									showOtherMonths : true
								});
									
								
							});
						} 
						
						$('.newsletter').click(function(){
							var email = $(this).siblings('input[type=text]');
							var value = email.val();
							if (isEmail(value)){
								var submit = {
							 			url : '/pub-news-letter/subscribe/',
							 			type : "POST",
							 			dataType : "json",
	    					 			  async: false,
							 			data  : {email : email.val()} ,
							 			success : function(data) {
							 				if (data && data.state && (data.state.indexOf("ERROR") != -1)) {
							 	 				alert(data.message);
							 					return;
							 				} else {
							 					email.val("");
							 					alert('thank you for you interesting');
							 				}
							 			}
					 	 		}
					 	 		$.ajax(submit);
								
								
								
								
							}else{
								alert('Please enter a valid email');
								email.focus();
							}
 
							
						});
						$('.searchBtn').each(function(index, value) {
 					 		var input =$(this).siblings('input:text');
					 		var target = $(this).attr('target');
					 		if (!target){
					 			target = 'search';
					 		}
  							input.keypress(function(event) {
 								
								var keycode = (event.keyCode ? event.keyCode : event.which);
								if (keycode == '13') {
									search(input.val(),target);
								}

							});
							$(this).click(function() {
								search(input.val(),target);

							});
						});	
						
						$('.reset-form').click(function(){
 							var form = $(this).parents('form:first');
 							cleanFrom(form);	
						});
						
 						$('.commentbtn').click(function(){
 							
							var form = $(this).parents('form:first');
 					 		if(!validateForm(form)){
 					 			return;
 					 		}
							var postId = form.attr('postid');
 				 	 		var submit = {
						 			url : '/pub-blog/'+postId+'/comment/',
						 			type : "POST",
						 			dataType : "json",
    					 			  async: false,
						 			data  : form.serialize() ,
						 			success : function(data) {
						 				if (data && data.state && (data.state.indexOf("ERROR") != -1)) {
						 	 				alert(data.message);
						 					return;
						 				} else {
											cleanFrom(form);
						 					showMessage('thanks for your common',form);
						 				}
						 			}
				 	 		}
				 	 		$.ajax(submit);
				 	 		
						});
 						
 						
 						$('.feedback').click(function() {
						
 							
 							
							var this_ = this;
							var form = $(this)
									.parents("form:first");
							if (!validateForm(form)){
 					 			return;
 					 		}
							
							var files = form.find("input[type = 'file']");
							var hasfile = files.length > 0;
								if (hasfile) {
								if (form.find('input[name="no_remove"]').length == 0){
								$('<input type="hidden" name="no_remove" value="true"/>').appendTo(form); 										
								}

							$io = $('<iframe />');
							$io.appendTo("body");
							$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
							
							
							var picform = $('<form enctype="multipart/form-data" method="post" />');
							setTimeout(function(){
							picform.appendTo($io.contents().find("body"));									
							
							
							
							},150);

								$(files).each(
									function(step, value) {
											$(value).clone().removeAttr("name").insertBefore($(value));
											$(value).attr("name","img-"+step);
										$(value).appendTo(picform);
										$("<input name='size'/>").val(files.length).appendTo(picform);
										$("<input name='captcha'/>").val(form.find("input[name = 'captcha']").val()).appendTo(picform);
 										}); 										
  							}
								
								setTimeout(function(){
							 						
									var submit = {
											url : '/pub-feed/feedback/',
											type : "POST",
											dataType : "json",
											data : form.serialize(),
											success : function(data) {
												if (data
														&& data.state
														&& (data.state
																.indexOf("ERROR") != -1)) {
													alert(data.message);
													processForm(form);
													//reloadcapcha();
													return;
												} else {
													if (hasfile){
												 	picform.attr('action','/pub-feed/'+data.entity.id+'/image/');
												 	$io.bind('load', function(){
			 											alert('thanks for your enquiry');
														processForm(form);
 			 									 	});
			 										picform.submit();
			 										}else{
													reloadcapcha();
													processForm(form);
													alert('thanks for your enquiry');
              
  													}
												
												

												}
											}}
									 
											$.ajax(submit);
									
									
									},200);


	
							
							
							});
 						
 						
 						

 	  					$(document).delegate('input:checkbox[value=true],input:checkbox[value=false]','click',
 											function() {
 	  											var val = $(this).val();
 	  											 
 	  											if ($(this).is(':checked')){
 	  												$(this).val("true");
 	  												var name = $(this).attr("name");
 	  												var xx=	$(this).siblings("[name="+name+"]")
 	  												xx.remove();

   	  											} else{
 	  												$(this).val("false");
 	 	  											var hidden = 	$("<input>",{
 	 	  													type :'hidden',
 	 	  													name : $(this).attr("name")
 	  	  												}).val("false");
 	  	  												hidden.insertAfter($(this));
   	  											}
 						});
 						

 						
 						
 	  					
 	  					$(document).delegate(".simple-submit","click",function(e){
  							if ($(this).attr("type")=='submit'){
 								e.preventDefault();
 								
 							}
 					 		var form =	$(this).parents("form:first");
 					 		var action = form.attr('action');
 					 		if (!validateForm(form)){
 					 			return;
 					 		}
 					 		if(typeof $.fn.ajaxSubmit == 'function'){
 					 	        var options = {
 					 	              success: function (data) {
 					 	            	  console.dir(data);
											if (data
													&& data.state
													&& (data.state
															.indexOf("ERROR") != -1)) {
												alert(data.message);
												var x = 	$(form).find("img.captcha");
													if (x){
														x.attr('src',x.attr('src'));		 																							
													}
  					 	              }
 					 	          }
  					 		}
  					 	        	$(form).ajaxSubmit(options);
   					 	 }
 					 		else{
									$
										.ajax({
											type : "POST",
											url  : action,
											data : form.serialize(),
											dataType : "json",
											success : function(data) {
												if (data
														&& data.state
														&& (data.state
																.indexOf("ERROR") != -1)) {
													alert(data.message);
													var x = 	$(form).find("img.captcha");
														if (x){
															x.attr('src',x.attr('src'));		 																							
														}
												} else {
													if (data.message){
														alert(data.message);
													}else{
														processForm(form);
														alert('Your request has been processed successfully');
													}
												
												}
											}
										}); 					 			
 					 		}
 


 					 	 	});
 						
 						
					 	$('#confirm[type=button] ,.resetpwd[type=button]').click(function(){
					 	 	if ($('#new').val()!= $('#pwd').val()){
					 	 		alert('password not same');
					 	 		return
					 	 	}
					 	 		var token =$("#token").val();
 					 	 		
					 	 		var submit = {
					 			url : '/pub-member/confirm/'+token+'/',
					 			type : "POST",
					 			dataType : "json",
					 			data  : {'password': $('#pwd').val()} ,
					 			success : function(data) {
					 				if (data && data.state && (data.state.indexOf("ERROR") != -1)) {
					 	 				alert(data.message);
					 					return;
					 				} else {
					 					alert('reset password successfully');
					 					windows.location.href= '/';
					 				}
					 			}
					 		};
					 		$.ajax(submit);
					 	 	})
		
  					$(document).delegate('.btnLogin','click',
										function(e) {
  											e.preventDefault();
    										login.apply(this);
  										});
						$('.forget')
								.click(
										function() {
											if (typeof (check) === 'function') {
												var l = check();
												if (!l) {
													return;
												}
											}
											var form = $("#forgetForm");
											if (form.length ==0){
											 
 												form = $(this).parents("form:first");
 											}
											if (form.valid){
												if (!form.valid()){
													return;
													
												}
											}
											
											$
													.ajax({
														type : "POST",
														url : "/pub-member/forget/",
														data : form
																.serialize(),
														dataType : "json",
														success : function(data) {
															if (data
																	&& data.state
																	&& (data.state
																			.indexOf("ERROR") != -1)) {
																alert(data.message);
															} else {
																alert('Password is recovered successfully. Please check your email.');
															}
														}
													});
										});

						$(document).delegate('.logout','click',function() {
											$
													.ajax({
														type : "POST",
														url : "/pub-member/logout/",
														data : $("#loginForm")
																.serialize(),
														dataType : "json",
														success : function(data) {

															if (data
																	&& data.state
																	&& (data.state
																			.indexOf("ERROR") != -1)) {
																alert(data.message);
															} else {
																window.location.href = '/';
															}
														}
													});
										});
						$('.formBtn')
								.click(
										function() {
											var this_ = this;

											var form = $(".cms_form");
											if (form.length ==0){
											 
 												form = $(this).parents("form:first");
 											}
											
											var submit = {
												url : '/pub-feed/feedback/',
												type : "POST",
												dataType : "json",
												data : form.serialize(),
												success : function(data) {
													if (data
															&& data.state
															&& (data.state
																	.indexOf("ERROR") != -1)) {
														alert(data.message);
														reloadcapcha();
														return;
													} else {
														reloadcapcha();
														alert('thanks for your enquiry');
														$(this_).attr(
																'disabled',
																'disabled');
													}
												}
											};
											$.ajax(submit);

										});

					$(document).delegate('.captcha','click',function() {
							var url = '/captcha/?' + new Date().getTime();
							$(this).attr('src', url);
						})

						$('input.input_radio:text').focus(function(val) {
							var container = $(this).siblings().last();
							var radio = $(container).find("input:radio");
							var name = radio.attr('name');
							name = (name.replace(".", "\\."));
							var $radios = $('input:radio[name=' + name + ']');
							$($radios).each(function(index, val) {
								var v = $(val).attr('value');
								if (v == 'Other') {
									$(val).prop('checked', true);
								} else {
									$(val).prop('checked', false);
								}
							});

						});
					}
				});